<?php

namespace core;

class Event {
    protected static $listeners = [];
    
    public static function listen($event, callable $listener) {
        if (!isset(self::$listeners[$event])) {
            self::$listeners[$event] = [];
        }
        self::$listeners[$event][] = $listener;
    }
    
    public static function trigger($event, $payload = []) {
        if (!isset(self::$listeners[$event])) {
            return;
        }
        
        foreach (self::$listeners[$event] as $listener) {
            call_user_func($listener, $payload);
        }
    }
    
    public static function subscribe($subscriber) {
        $methods = get_class_methods($subscriber);
        
        foreach ($methods as $method) {
            if (strpos($method, 'on') === 0) {
                $event = lcfirst(substr($method, 2));
                self::listen($event, [$subscriber, $method]);
            }
        }
    }
}